package hidalgo.expenses.adapter;

import java.util.ArrayList;

import hidalgo.expenses.entities.Account;
import hidalgo.expenses.widgets.AccountItemView;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

public class AccountViewAdapter extends ArrayAdapter<Account> {

	private Context context;
	private ArrayList<Account> accountList;

	public AccountViewAdapter(Context context, int textViewResourceId,
			ArrayList<Account> accountList) {
		super(context, textViewResourceId);
		this.context = context;
		this.accountList = accountList;

	}

	@Override
	public int getCount() {
		return accountList.size();
	}

	@Override
	public Account getItem(int position) {
		return accountList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return accountList.get(position).getAccountId();
	}

	public void updateAccount(Account account) {
		for (int i = 0; i < accountList.size(); i++) {
			if (accountList.get(i).getAccountId() == account.getAccountId()) {
				accountList.set(i, account);
				break;
			}
		}
	}

	public void addAccount(Account account) {
		accountList.add(account);
	}

	public void removeAccount(int accountId) {

		for (int i = 0; i < accountList.size(); i++) {
			if (accountList.get(i).getAccountId() == accountId) {
				accountList.remove(i);
				break;
			}
		}
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		AccountItemView accountItemView = new AccountItemView(context);
		accountItemView.setAccount(accountList.get(position));

		return accountItemView;
	}

}
